<template>
  <div class="addBrand-container" id="food-add-app">
    <div class="container">
      <el-form
          ref="formRef"
          :model="ruleForm"
          :rules="rules"
          label-width="180px"
          class="demo-ruleForm"
      >
        <!-- 菜品名称 -->
        <el-form-item label="菜品名称:" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请填写菜品名称" maxlength="20" />
        </el-form-item>

        <!-- 菜品分类 -->
        <el-form-item label="菜品分类:" prop="categoryId">
          <el-select v-model="ruleForm.categoryId" placeholder="请选择菜品分类">
            <el-option
                v-for="(item, index) in dishList"
                :key="index"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 菜品价格 -->
        <el-form-item label="菜品价格:" prop="price">
          <el-input v-model="ruleForm.price" placeholder="请设置菜品价格" />
        </el-form-item>

        <!-- 口味配置 -->
        <el-form-item label="口味做法配置:">
          <div class="flavorBox">
            <span class="addBut" @click="addFlavore">+ 添加口味</span>

            <div v-if="dishFlavors.length > 0" class="flavor">
              <div class="title">
                <span>口味名（3个字内）</span><span>口味标签（输入标签回车添加）</span>
              </div>
              <div class="cont">
                <div v-for="(item, index) in dishFlavors" :key="index" class="items">
                  <div class="itTit">
                    <div class="selectInput">
                      <el-input
                          v-model="item.name"
                          placeholder="请输入口味"
                          @focus="selectFlavor(true, index)"
                          @blur="outSelect(false, index)"
                          @input="inputHandle(index)"
                      />
                      <div v-show="item.showOption" class="flavorSelect">
                        <span
                            v-for="(it, ind) in dishFlavorsData"
                            :key="ind"
                            class="items"
                            @click="checkOption(it, ind, index)"
                        >{{ it.name }}</span>
                        <span v-if="!dishFlavorsData.length" class="none">无数据</span>
                      </div>
                    </div>
                  </div>
                  <div class="labItems" style="display: flex">
                    <span v-for="(it, ind) in item.value" :key="ind">
                      {{ it }} <i @click="delFlavorLabel(index, ind)">X</i>
                    </span>
                    <div
                        class="inputBox"
                        contenteditable="true"
                        @focus="flavorPosition(index)"
                        @keydown.enter="(e) => keyDownHandle(e, index)"
                    ></div>
                  </div>
                  <span class="delFlavor delBut non" @click="delFlavor(index)">删除</span>
                </div>
              </div>
              <div class="addBut" @click="addFlavore">添加口味</div>
            </div>
          </div>
        </el-form-item>

        <!-- 菜品图片 -->
        <el-form-item label="菜品图片:" prop="region" class="uploadImg">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/common/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :on-change="onChange"
              ref="upload"
              :auto-upload="true"
          >
            <!-- 显示图片 -->
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <!-- 默认图标 + 按钮 -->
            <div v-else>
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <div style="font-size: 12px; color: #666; margin-top: 8px;">点击上传图片</div>
            </div>
            <!-- 添加按钮文字 -->
            <el-button type="primary" size="small" style="margin-top: 10px;">
              {{ imageUrl ? '重新上传' : '选择图片' }}
            </el-button>
          </el-upload>
        </el-form-item>

        <!-- 描述 -->
        <el-form-item label="菜品描述:">
          <el-input
              v-model="ruleForm.description"
              type="textarea"
              :rows="3"
              placeholder="菜品描述，最长200字"
              maxlength="200"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <div class="subBox address">
          <el-form-item>
            <el-button @click="goBack">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
            <el-button
                v-if="actionType === 'add'"
                type="primary"
                class="continue"
                @click="submitForm('ruleForm', 'goAnd')"
            >保存并继续添加菜品</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import {
  getCategoryList,
  queryDishById,
  addDish,
  editDish
} from '@/api/food'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()
const route = useRoute()

// 数据定义
const id = ref('')
const actionType = ref('add')
const ruleForm = ref({
  name: '',
  price: '',
  description: '',
  categoryId: '',
  image: '',
  status: true,
  dishFlavors: []
})

const imageUrl = ref('')
const upload = ref(null)
const dishList = ref([])
const dishFlavorsData = ref([
  { name: '甜味', value: ['无糖', '少糖', '半糖', '多糖', '全糖'] },
  { name: '温度', value: ['热饮', '常温', '去冰', '少冰', '多冰'] },
  { name: '忌口', value: ['不要葱', '不要蒜', '不要香菜', '不要辣'] },
  { name: '辣度', value: ['不辣', '微辣', '中辣', '重辣'] }
])
const dishFlavors = ref([])
const inputStyle = ref({ flex: 1 })
const index = ref(0)

// 表单验证规则
const validatePrice = (rule, value, callback) => {
  const reg = /^\d+(\.\d{0,2})?$/
  if (!value) {
    callback(new Error('请填写菜品价格'))
  } else if (!reg.test(value)) {
    callback(new Error('菜品价格格式只能为数字，且最多保留两位小数'))
  } else if (value >= 10000) {
    callback(new Error('菜品价格必须小于10000'))
  } else {
    callback()
  }
}

const rules = {
  name: [{ required: true, message: '请填写菜品名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择菜品分类', trigger: 'change' }],
  price: [{ required: true, validator: validatePrice, trigger: 'blur' }]
}

// 获取菜品分类
const getDishList = async () => {
  const res = await getCategoryList({ type: 1 })
  if (res.code === 1) {
    dishList.value = res.data
  } else {
    ElMessage.error(res.msg || '操作失败')
  }
}

// 获取 URL 参数
const init = async () => {
  const search = new URLSearchParams(window.location.search)
  id.value = search.get('id')
  actionType.value = id.value ? 'edit' : 'add'

  if (id.value) {
    try {
      const res = await queryDishById(id.value)
      if (res.code === 1) {
        ruleForm.value = { ...res.data }
        ruleForm.value.price = String(res.data.price / 100)
        ruleForm.value.status = res.data.status === '1'
        dishFlavors.value = res.data.flavors?.map(obj => ({
          ...obj,
          value: JSON.parse(obj.value),
          showOption: false
        })) || []
        imageUrl.value = `/common/download?name=${res.data.image}`
      } else {
        ElMessage.error(res.msg || '操作失败')
      }
    } catch (err) {
      ElMessage.error('请求出错了：' + err)
    }
  }
}

// 添加口味
const addFlavore = () => {
  dishFlavors.value.push({ name: '', value: [], showOption: false })
}

// 删除口味
const delFlavor = (ind) => {
  dishFlavors.value.splice(ind, 1)
}

// 删除口味标签
const delFlavorLabel = (index, ind) => {
  dishFlavors.value[index].value.splice(ind, 1)
}

// 记录当前输入位置
const flavorPosition = (index) => {
  index.value = index
}

// 输入回车添加口味标签
const keyDownHandle = (event, index) => {
  event.preventDefault()
  const text = event.target.innerText.trim()
  if (text) {
    dishFlavors.value[index].value.push(text)
    event.target.innerText = ''
  }
}

// 获取分类列表
onMounted(() => {
  getDishList()
  init()
})

// 提交表单
const submitForm = async (formName, st) => {
  const valid = await validateForm(formName)
  if (valid) {
    const params = {
      ...ruleForm.value,
      price: ruleForm.value.price * 100,
      flavors: dishFlavors.value.map(f => ({ ...f, value: JSON.stringify(f.value) }))
    }

    if (!imageUrl.value) {
      ElMessage.error('请上传菜品图片')
      return
    }

    try {
      let res
      if (actionType.value === 'add') {
        delete params.id
        res = await addDish(params)
        if (res.code === 1) {
          ElMessage.success('菜品添加成功！')
          if (!st) {
            goBack()
          } else {
            dishFlavors.value = []
            imageUrl.value = ''
            ruleForm.value = {
              name: '',
              price: '',
              code: '',
              image: '',
              description: '',
              dishFlavors: [],
              status: true,
              categoryId: ''
            }
          }
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      } else {
        res = await editDish({ ...params, id: id.value })
        if (res.code === 1) {
          ElMessage.success('菜品信息修改成功！')
          goBack()
        } else {
          ElMessage.error(res.msg || '操作失败')
        }
      }
    } catch (err) {
      ElMessage.error('请求出错了：' + err)
    }
  }
}

// 返回上一页
const goBack = () => {
  window.parent.menuHandle(
      { id: '4', url: '/backend/page/food/list.html', name: '菜品管理' },
      false
  )
}

// 验证表单
const formRef = ref(null)
const validateForm = (formName) => {
  return new Promise((resolve) => {
    formRef.value.validate(valid => resolve(valid))
  })
}

// 上传头像成功
const handleAvatarSuccess = (response) => {
  if (response.code === 0 && response.msg === '未登录') {
    window.top.location.href = '/backend/page/login/login.html'
  } else {
    imageUrl.value = `/common/download?name=${response.data}`
    ruleForm.value.image = response.data
  }
}

// 文件校验
const onChange = (file) => {
  if (file) {
    const suffix = file.name.split('.')[1]
    const size = file.size / 1024 / 1024 < 2

    if (!['png', 'jpeg', 'jpg'].includes(suffix.toLowerCase())) {
      ElMessage.error('上传图片只支持 png、jpeg、jpg 格式！')
      upload.value.clearFiles()
      return false
    }
    if (!size) {
      ElMessage.error('上传文件大小不能超过 2MB!')
      return false
    }
    return file
  }
}
</script>

<style scoped>
.selectInput {
  position: relative;
  width: 100%;
  min-width: 100px;
}
.selectInput .flavorSelect {
  position: absolute;
  width: 100%;
  padding: 0 10px;
  border-radius: 3px;
  border: solid 1px #ff903d;
  line-height: 30px;
  background: #fff;
  top: 50px;
  z-index: 99;
}
.selectInput .flavorSelect .items {
  cursor: pointer;
  display: inline-block;
  width: 100%;
  line-height: 35px;
  border-bottom: solid 1px #f4f4f4;
  color: #666;
}
.selectInput .flavorSelect .none {
  font-size: 14px;
}
#food-add-app .uploadImg .el-form-item__label::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>
